from service.channel_service import *
from service.common_service import get_records, do_api
from service.pending_service import get_pending_send_param
from service.scene_service import *
from service.upgrade_service import *
app = Flask(__name__)
db_client = MySQLClient(db_config)
tenant_db_client = MySQLClient(tenant_db_config)
refact_db_client = MySQLClient(refact_db_config)

@app.route('/')
def index():
    return render_template('index.html', active_page='home')

@app.route('/channel')
def channel():
    action = 'message_send'
    records = get_records(action)
    table_name = MyEnv.table_name[action]
    return render_template('channel.html', records=records, action=action, table_name=table_name, active_page=action)

@app.route('/scene')
def scene():
    action = 'scene_send'
    records = get_records(action,request.args.get('type'))
    table_name = MyEnv.table_name[action]
    return render_template('scene.html', records=records, action=action, table_name=table_name, active_page=action)

@app.route('/pending')
def pending():
    action = 'pending_send'
    records = get_records(action)
    table_name = MyEnv.table_name[action]
    return render_template('pending.html', records=records, action=action, table_name=table_name, active_page=action)

@app.route('/do_api', methods=['POST'])
def do_api_route():
    request_body = request.json.get('request_body')
    url = request.json.get('url')
    auth = request.json.get('auth')
    tenant_code = request.json.get('tenant_code')
    return do_api(url, auth, tenant_code, request_body)

@app.route('/get_channel_send_param')
def get_channel_send_param_route():
    return get_channel_send_param(request.args.get('id'))

@app.route('/get_channel_update_status_param')
def get_update_param_route():
    return get_update_param(request.args.get('id'))


@app.route('/get_channel_delete_by_biz_id_param')
def get_channel_delete_param_route():
    return get_channel_delete_param(request.args.get('id'))


@app.route('/get_channel_delete_by_business_id_param')
def get_channel_delete_by_business_id_param_route():
    return get_channel_delete_by_business_id_param(request.args.get('id'))

@app.route('/get_channel_batch_delete_param')
def get_channel_batch_delete_param_route():
    return get_channel_batch_delete_param(request.args.get('id'))

@app.route('/get_scene_send_param')
def get_scene_send_param_route():
    return get_scene_send_param(request.args.get('id'))

@app.route('/get_pending_send_param')
def get_pending_send_param_route():
    return get_pending_send_param(request.args.get('id'))

@app.route('/get_scene_update_status_param')
def get_scene_update_status_param_route():
    return get_scene_update_status_param(request.args.get('id'))

@app.route('/get_scene_delete_by_biz_id_param')
def get_scene_delete_by_biz_id_param_route():
    return get_scene_delete_by_biz_id_param(request.args.get('id'))

@app.route('/get_scene_delete_by_business_id_param')
def get_scene_delete_by_business_id_param_route():
    return get_scene_delete_by_business_id_param(request.args.get('id'))

@app.route('/query_result_api')
def query_result_api():
    action = request.args.get('action')
    biz_id = request.args.get('biz_id')
    businessGuid = request.args.get('businessGuid')
    btnText = request.args.get('btnText')

    if "business_id" in btnText:
        sql = "select requestGUID from " + MyEnv.new_table_name[action] + " where requestBody like %s order by CreatedTime desc limit 1"
        requestGUID = refact_db_client.query(sql,[f"%{businessGuid}%"])[0][0]
    else:
        sql = "select requestGUID from " + MyEnv.new_table_name[action] + " where bizId=%s order by CreatedTime desc limit 1"
        requestGUID = refact_db_client.query(sql, [biz_id])[0][0]

    sql = "SELECT stepRank,stepName,exceptionMessage,status from ggfw_mum_log WHERE requestGUID=%s order by stepRank"
    records = refact_db_client.query(sql, [requestGUID])

    sql_show = sql % ("'%s'" % requestGUID if requestGUID else "NULL")

    return jsonify({'requestGUID': requestGUID, 'records': records, 'sql': sql_show})

@app.route('/compare')
def compare():
    action = request.args.get('action')
    biz_id = request.args.get('biz_id')
    businessGuid = request.args.get('businessGuid')
    p = [biz_id]
    if businessGuid:
        p.append(businessGuid)
    old_fields_sql = ("`openid`, `type`, `msg_type`, `app_code`, `app_id`, `app_type`, `module_code`, `module_id`, "
                      "`msg_channel`, `biz_id`, `msg_content`, `app_extra`, `pc_extra`, `start_time`, `end_time`, "
                      "`status`, `is_enable`, `is_need_click`, `emergency_degree`, `business_guid`, `business_type`, "
                      "`bu_guid`, `proj_guids`, `owner`, `sender_name`, `sender_id`, `sender_code`, `done_at`, "
                      "`published_at`, `mip_event`, `has_distribute`")

    old_app_sql = "SELECT " + old_fields_sql + " FROM view_mum_msg_user_message WHERE msg_channel=1 and biz_id=%s"
    if businessGuid:
        old_app_sql += " and business_guid=%s"
    old_app_result = tenant_db_client.query(old_app_sql, p)
    old_app_value = old_app_result[0] if old_app_result else None
    old_app_value = row_to_dict(old_fields_sql, old_app_value)

    old_pc_sql = "SELECT " + old_fields_sql + " FROM view_mum_msg_user_message WHERE msg_channel=2 and biz_id=%s"
    if businessGuid:
        old_pc_sql += " and business_guid=%s"
    old_pc_result = tenant_db_client.query(old_pc_sql, p)
    old_pc_value = old_pc_result[0] if old_pc_result else None
    old_pc_value = row_to_dict(old_fields_sql, old_pc_value)

    new_fields_sql = (
        "`userGUID` AS `openid`,`type`,`msgType` AS `msg_type`,`appCode` AS `app_code`,`appId` AS `app_id`,"
        "`appType` AS `app_type`,`moduleCode` AS `module_code`,`moduleId` AS `module_id`,`msgChannel` "
        "AS `msg_channel`,`bizId` AS `biz_id`,`msgContent` AS `msg_content`,`appExtra` AS `app_extra`,"
        "`pcExtra` AS `pc_extra`,`startTime` AS `start_time`,`endTime` AS `end_time`,`status`,"
        "`isEnable` AS `is_enable`,`isNeedClick` AS `is_need_click`,`emergencyDegree` AS "
        "`emergency_degree`,`businessGUID` AS `business_guid`,`businessType` AS `business_type`,"
        "`buGUID` AS `bu_guid`,`projGUIDs` AS `proj_guids`,`owner`,`senderName` AS `sender_name`,"
        "`senderId` AS `sender_id`,`senderCode` AS `sender_code`,`doneAt` AS `done_at`,`publishedAt` AS "
        "`published_at`,`mipEvent` AS `mip_event`,`hasDistribute` AS `has_distribute`")
    new_app_sql = "SELECT " + new_fields_sql + (" FROM " + MyEnv.new_result_table_name[action] +" WHERE msgchannel=1 and bizid=%s")
    if businessGuid:
        new_app_sql += " and businessGUID=%s"
    new_app_sql += "order by CreatedTime desc limit 1"
    new_app_result = refact_db_client.query(new_app_sql, p)
    new_app_value = new_app_result[0] if new_app_result else None
    new_app_value = row_to_dict(old_fields_sql, new_app_value)

    new_pc_sql = "SELECT " + new_fields_sql + (
                " FROM " + MyEnv.new_result_table_name[action] + " WHERE msgchannel=2 and bizid=%s")
    if businessGuid:
        new_pc_sql += " and businessGUID=%s"
    new_pc_sql += "order by CreatedTime desc limit 1"
    new_pc_result = refact_db_client.query(new_pc_sql, p)
    new_pc_value = new_pc_result[0] if new_pc_result else None
    new_pc_value = row_to_dict(old_fields_sql, new_pc_value)
    return render_template('compare.html', old_app_value=old_app_value, old_pc_value=old_pc_value,
                           new_app_value=new_app_value, new_pc_value=new_pc_value)


def row_to_dict(fields_sql, row):
    field_names = [f.strip(' `') for f in fields_sql.split(',')]

    if row:
        return dict(zip(field_names, row))
    return None

@app.route('/upgrade_accessor')
def upgrade_accessor_route():
    return upgrade_accessor()

@app.route('/upgrade_strategy')
def upgrade_strategy_route():
    return upgrade_strategy()

@app.route('/upgrade_strategy_channel_rule')
def upgrade_strategy_channel_rule_route():
    return upgrade_strategy_channel_rule()

@app.route('/upgrade_accessor_strategy')
def upgrade_accessor_strategy_route():
    return upgrade_accessor_strategy()


if __name__ == '__main__':
    app.run(debug=True)
